import Fly from 'flyio/dist/npm/fly'
import store from '@/store'
import { Toast } from 'vant'
import { API_BASE } from '@/libs/config'
const fly = new Fly()
fly.config.baseURL = API_BASE
fly.config.timeout = 10000
// fly.config.withCredentials = true
// request.url.indexOf('account/sendRegisterMsg') !== -1 || request.url.indexOf('account/register') !== -1 || request.url.indexOf('account/sendResetMsg') !== -1 || request.url.indexOf('account/resetPassowrd') !== -1 || request.url.indexOf('userInfo/updatePhone') !== -1 || request.indexOf('userInfo/sendUpdatePhoneMsg') !== -1 || request.indexOf('userInfo/sendBindPhoneMsg') !== -1 || request.indexOf('userInfo/bindPhone') !== -1
const credentialUrl = ['account/sendRegisterMsg', 'account/register', 'account/sendResetMsg', 'account/resetPassowrd', 'userInfo/updatePhone', 'userInfo/sendUpdatePhoneMsg', 'userInfo/sendBindPhoneMsg', 'userInfo/bindPhone']
// 添加请求拦截器
fly.interceptors.request.use(request => {
  if (credentialUrl.findIndex((item) => {
    return request.url.indexOf(item) !== -1
  }) !== -1) {
    // console.log('msg')
    request.withCredentials = true
  } else {
    request.withCredentials = false
  }
  // console.log(request)
  // 给所有请求添加自定义header
  request.headers['Authorization'] = store.getters.tokenHeader // token
  // 终止请求
  // var err=new Error("xxx")
  // err.request=request
  // return Promise.reject(new Error(""))

  // 可以显式返回request, 也可以不返回，没有返回值时拦截器中默认返回request
  return request
})

// 添加响应拦截器，响应拦截器会在then/catch处理之前执行
fly.interceptors.response.use(
  response => {
    // 只将请求结果的data字段返回
    // console.log(response)
    return response.data
  },
  err => {
    // 发生网络错误后会走到这里
    // console.log('err', err)
    let errorCode = err.status
    switch (errorCode) {
      case 401:
        if (err.request.url.indexOf('account/oauth2/refresh_token') !== -1) {
          Toast('登录已过期，请重新登录')
          store.dispatch('logout')
        } else {
          store.dispatch('refreshToken')
        }
        break
      case 404:
        Toast('404 Error，访问的接口不存在')
        break
      case 500:
        Toast('500 Error, 服务器出错了')
        break
      case 1:
        Toast('请求超时，请重试')
        break
      default:
        Toast('请求错误，请重试')
        break
    }

    return err
  }
)

export default fly
